package com.kunbo.service;

import com.kunbo.entity.Ticket;
import com.kunbo.entity.User;
import com.kunbo.mapper.TicketMapper;
import com.kunbo.mapper.UserMapper;
import com.kunbo.util.CommunityConstant;
import com.kunbo.util.Md5;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.management.GarbageCollectorMXBean;
import java.util.*;

@Service
public class UserService implements CommunityConstant {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TicketMapper ticketMapper;

    public User findUserById(int id){
        return userMapper.selectById(id);
    }

    public User findUserByName(String userName){
        return userMapper.selectByName(userName);
    }

    public int updateStatus(int id, int status){
        return userMapper.updateStatus(id, status);
    }

    /**
     *
     * @param username 传入的用户名
     * @param password 传入的密码
     * @param expiredSeconds 传入的过期时间
     * @return
     */
    public Map<String, Object> login(String username, String password, int expiredSeconds){
        Map<String, Object> map = new HashMap<>();

        //空值处理
        if(StringUtils.isBlank(username)){
            map.put("usernameMsg", "用户名不能为空");
            return map;
        }
        if(StringUtils.isBlank(password)){
            map.put("passwordMsg", "密码不能为空");
            return map;
        }

        //验证账号合法性
        User user = userMapper.selectByName(username);
        if(user == null){
            map.put("usernameMsg", "账号不存在");
            return map;
        }

        //验证账号状态
        if(user.getStatus() == 0){
            map.put("usernameMsg", "该账号未激活");
            return map;
        }

        //验证密码
        if(!user.getPassword().equals(password)){
            map.put("passwordMsg", "密码不正确");
            return map;
        }

        //生成登录凭证
        Ticket ticket = new Ticket();
        ticket.setUserId(user.getId());
        ticket.setTicket(Md5.md5(user.getUsername() + new Date()));
        ticket.setStatus(1);
        ticket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));
        ticketMapper.insertLoginTicket(ticket);

        map.put("ticket", ticket.getTicket());

        return map;
    }

    //根据Ticket查找用户
    public User findUserByTicket(String ticket) {
        int userId = findLoginTicket(ticket).getUserId();
        return findUserById(userId);
    }

    //注册业务
    @Transactional//代表是一个事务
    public Map<String, Object> register(User user){
        Map<String, Object> map = new HashMap<>();
        if(user == null){
            throw new IllegalArgumentException("参数不能为空");
        }
        if(StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg", "用户名不能为空");
            return map;
        }
        if(StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg", "密码不能为空");
            return map;
        }
        //验证是否存在该user
        User u = userMapper.selectByName(user.getUsername());
        if(u != null){
            map.put("userMsg", "该账号已经存在");
            return map;
        }
        userMapper.insertUser(user);
        return map;
    }

    //登出业务
    public void logout(String ticket){
        ticketMapper.updateStatus(ticket, 0);
    }

    //查找对应的logTicket
    public Ticket findLoginTicket(String ticket){
        return ticketMapper.selectByTicket(ticket);
    }


//    public Collection<? extends GrantedAuthority> getAuthorities(int userId){
//        User user = this.findUserById(userId);
//
//        List<GrantedAuthority> list = new ArrayList<>();
//        list.add(new GrantedAuthority() {
//            @Override
//            public String getAuthority() {
//                switch (user.getId()){
//                    case 2://GOD
//                        return AUTHORITY_GOD;
//                    case 1:
//                        return AUTHORITY_ADMIN;
//                    case 0:
//                        return AUTHORITY_USER;
//                }
//                return null;
//            }
//        });
//        return list;
//    }

}
